<template>
  <div class="add-record">
    <div class="e-nav-bar">
      <div>
        <van-icon class="e-nav-bar__back" name="arrow-left" size="24" @click="back" />
      </div>
      <div class="e-nav-bar__title e-flex-y-center">
        <div class="e-f-24 e-bold" style="min-width:96px;">添加记录</div>
        <van-search class="e-search e-flex-fill" v-model="selectStr" placeholder="搜一搜" @search="search()" />
        <van-popover ref="popover" v-model="showPopover" trigger="click" :offset="[-85,5]">
          <div class="e-p-10">
            <div
              v-for="n in actions"
              :key="n.id"
              class="e-pt-10 e-pb-10 e e-f-14"
              :class="n.active?'e-color-primary':'e-color-999'"
              style="width:180px;"
              @click="selectAction(n)"
            >{{n.name}}</div>
            <van-button class="e-mt-10" type="info" plain size="small" style="width:100%;" @click="clearFilter">清空</van-button>
          </div>
          <template #reference>
            <div class="e-flex-y-center e-flex-between e-p-5">
              <i class="iconfont icon-weibiaoti-_shaixuan e-f-18" :class="{'e-color-primary':orgId||deviceTypes||deviceCategoryId||deviceStartTime}"></i>
            </div>
          </template>
        </van-popover>
      </div>
    </div>
    <div style="height:90px;"></div>
    <div class="e-pl-15 e-pr-15 e-pb-5">
      <div class="e-tabs e-flex-y-center">
        <div class="e-tabs-item" :class="{'is-active':tabId==1}" @click="tabId=1;list=[];search()">全部</div>
        <div class="e-tabs-item" :class="{'is-active':tabId==2}" @click="tabId=2;list=[];search()">未上传数据设备</div>
      </div>
      <div v-show="tabId==2" class="e-flex-y-center e-flex-around e-mt-20">
        <van-tag :color="timeTag==1?'#3B6FC4':'#999'" size="large" plain @click="dataTimeChange(1)">近三天</van-tag>
        <van-tag :color="timeTag==2?'#3B6FC4':'#999'" size="large" plain @click="dataTimeChange(2)">近七天</van-tag>
        <van-tag
          :color="timeTag==3?'#3B6FC4':'#999'"
          size="large"
          plain
          @click="dataTimeChange(3)"
        >{{timeTag==3&&dataStartTime?dataStartTime+'~今天':'自定义'}}</van-tag>
      </div>
    </div>

    <div ref="listWrap" class="add-record-list e-relative" :class="'is-tab'+tabId">
      <van-loading v-show="loading" />
      <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
        <van-list v-model="loading" :finished="finished" finished-text @load="getList">
          <div class="e-pl-15 e-pr-15 e-pb-15">
            <div v-for="n in list" :key="n.id" class="add-record-item e-p-15 e-mt-15" @click="goDetail(n)">
              <div class="e-f-18">{{n.name}}</div>
              <div class="e-f-14 e-color-999 e-mt-3">{{n.aliasName||'编码'}}：{{n.deviceId}}</div>
              <div class="e-f-14 e-color-999 e-mt-3">添加设备时间：{{n.createTime}}</div>
              <div class="e-f-14 e-color-999 e-mt-3">所属单位：{{n.orgName}}</div>
              <div v-if="n.fbsName" class="e-f-14 e-color-999 e-mt-3">安装位置：{{n.fbsName}}>{{n.localtion}}</div>
              <div class="e-f-14 e-color-999 e-mt-3">最新数据上传时间：{{n.dataTime}}</div>
              <div class="e-flex-y-center e-flex-end e-mt-10">
                <van-button class="van-button--theme" @click.stop="goForm(n)">修改</van-button>
                <van-button class="e-ml-10" type="default" @click.stop="askDel(n)">删除</van-button>
              </div>
            </div>
          </div>
        </van-list>
        <van-empty v-if="nodata" description="暂无数据" />
      </van-pull-refresh>
    </div>

    <van-overlay :show="showPopover" z-index="10" @click="showPopover = false" />

    <!-- 选择单位 -->
    <unit-picker v-if="userInfo.isMuilUnitUser" ref="UnitPicker" :showButton="false" @change="onUnitChange"></unit-picker>

    <van-calendar
      v-model="showCalendar"
      :title="calendarTitle"
      :type="calendarKey==1?'single':'range'"
      color="#2471CA"
      :default-date="calendarKey==1?defaultDate1:defaultDate2"
      :min-date="minDate"
      :max-date="maxDate"
      @confirm="confirmCalendar"
    />

    <van-overlay class="e-flex-xy-center" :show="loadingMask" z-index="9" style="background: none;">
      <van-loading size="40px" color="#333" />
    </van-overlay>

    <van-popup v-model="typePopup" position="bottom" :style="{ height: '50%' }">
      <van-picker
        show-toolbar
        title="设备类型"
        :columns="typeColumns"
        value-key="name"
        :visible-item-count="5"
        @confirm="typeChange"
        @cancel="typePopup=false"
      />
    </van-popup>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { getInsertList, delDevice } from '@/api/device'
import UnitPicker from '@/components/UnitPicker'
let today = new Date()
export default {
  name: 'AddRecord',
  components: { UnitPicker },

  data() {
    return {
      orgId: '',
      orgName: '',
      tabId: 1,
      selectStr: '',
      pageIndex: 0,
      pageSize: 20,
      list: [],
      isLoading: false,
      loading: false,
      finished: false,
      nodata: false,
      show: false,
      showPopover: false,
      showCalendar: false,
      calendarKey: 1,
      calendarTitle: '',
      dataStartTime: '',
      dataEndTime: '',
      defaultDate1: today,
      deviceStartTime: '',
      deviceEndTime: '',
      deviceTimeTxt: '',
      defaultDate2: [today, today],
      minDate: new Date(2019, 0, 1),
      maxDate: today,
      loadingMask: false,
      typeColumns: [],
      typePopup: false,
      typeName: '',
      deviceTypes: '',
      deviceCategoryId: '',
      timeTag: 1,
    }
  },

  computed: {
    ...mapState(['userInfo', 'userOrgIds']),
    actions() {
      let arr = [
        {
          id: '3',
          name: this.deviceTimeTxt || '添加设备时间',
          active: this.deviceStartTime,
        },
      ]
      arr.unshift({
        id: '4',
        name: this.typeName || '设备类型',
        active: this.deviceTypes || this.deviceCategoryId,
      })
      if (this.userInfo.isMuilUnitUser) {
        arr.unshift({
          id: '1',
          name: this.orgName || '选择单位',
          active: this.orgId,
        })
      }
      return arr
    },
  },

  watch: {
    showPopover() {
      this.$nextTick(() => {
        this.$refs.popover.$refs.popover.$el.classList.add(
          'popover-device-filter'
        )
      })
    },
  },

  created() {
    this.dataStartTime = this.$moment().subtract(2, 'days').format('yyyy-MM-DD')
    this.dataEndTime = this.$moment().format('yyyy-MM-DD')
    if (this.$route.params.typeOptions) {
      this.typeColumns = this.$route.params.typeOptions
    }
  },

  activated() {
    console.log('AddRecord activated')
    if (this.inited) {
      this.search()
    }
    this.inited = true
  },

  methods: {
    dataTimeChange(type) {
      let end = this.$moment().format('yyyy-MM-DD')
      if (type == 1) {
        this.timeTag = type
        this.dataStartTime = this.$moment()
          .subtract(2, 'days')
          .format('yyyy-MM-DD')
        this.dataEndTime = end
        this.search()
      } else if (type == 2) {
        this.timeTag = type
        this.dataStartTime = this.$moment()
          .subtract(6, 'days')
          .format('yyyy-MM-DD')
        this.dataEndTime = end
        this.search()
      } else if (type == 3) {
        this.dataEndTime = end
        this.openCalendar(1)
      }
    },
    typeChange(val, indexs) {
      this.deviceTypes = this.typeColumns[indexs[0]].id
      this.deviceCategoryId = this.typeColumns[indexs[0]].children[indexs[1]].id
      if (this.deviceCategoryId) {
        this.typeName = this.typeColumns[indexs[0]].children[indexs[1]].name
      } else if (this.deviceTypes) {
        this.typeName = this.typeColumns[indexs[0]].name
      } else {
        this.typeName = ''
      }
      this.search()
      this.typePopup = false
    },
    goDetail(n) {
      if (n.businessType == 2) {
        this.$router.push({
          name: 'DtuData',
          params: {
            deviceNo: n.recordId,
            name: n.name,
          },
        })
        return
      }
      window.top.goDeviceDetail({
        fcFacilitiesId: n.recordId,
      })
    },
    onUnitChange(val) {
      this.orgId = val.organizationId
      this.orgName = val.shortName || '选择单位'
      this.search()
    },
    selectAction(n) {
      if (n.id == 1) {
        this.openUnit()
      } else if (n.id == 3) {
        this.openCalendar(2)
      } else if (n.id == 4) {
        this.typePopup = true
      }
    },
    openUnit() {
      this.$refs.UnitPicker.active = true
    },
    openCalendar(key) {
      this.calendarKey = key
      this.calendarTitle = key == 1 ? '数据上传时间' : '添加设备时间'
      this.showCalendar = true
    },
    confirmCalendar(val) {
      if (this.calendarKey == '1') {
        this.dataStartTime = this.$moment(val).format('yyyy-MM-DD')
        this.timeTag = 3
      } else {
        let begin = this.$moment(val[0]).format('yyyy-MM-DD')
        let end = this.$moment(val[1]).format('yyyy-MM-DD')
        let item = this.actions.find((n) => {
          return n.id == 3
        })
        this.deviceStartTime = begin
        this.deviceEndTime = end
        item.active = true
        this.deviceTimeTxt = begin + '~' + end
      }
      this['defaultDate' + this.calendarKey] = val
      this.showCalendar = false
      this.search()
    },
    clearFilter() {
      this.orgId = ''
      this.orgName = ''
      this.deviceStartTime = ''
      this.deviceEndTime = ''
      this.deviceTimeTxt = ''
      this.defaultDate2 = []
      this.deviceTypes = ''
      this.deviceCategoryId = ''
      this.typeName = ''
      this.search()
      this.showPopover = false
    },
    onRefresh() {
      this.pageIndex = 0
      this.getList()
    },
    search() {
      this.loading = true
      this.pageIndex = 0
      this.getList()
    },
    getList() {
      let params = {
        account: this.userInfo.accountName,
        orgIds: this.orgId || this.userOrgIds,
        flag: this.tabId,
        selectStr: this.selectStr,
        pageIndex: this.pageIndex,
        pageSize: this.pageSize,
        deviceStartTime: this.deviceStartTime
          ? this.deviceStartTime + ' 00:00:00'
          : '',
        deviceEndTime: this.deviceEndTime
          ? this.deviceEndTime + ' 23:59:59'
          : '',
        deviceTypes: this.deviceTypes,
        deviceCategoryId: this.deviceCategoryId,
      }
      if (this.tabId == 2) {
        params.dataStartTime = this.dataStartTime + ' 00:00:00'
        params.dataEndTime = this.dataEndTime + ' 23:59:59'
      } else {
        params.dataStartTime = ''
        params.dataEndTime = ''
      }
      getInsertList(params)
        .then(({ data }) => {
          if (this.pageIndex == 0) {
            this.list = data
            this.$nextTick(() => {
              this.$refs.listWrap.scrollTo(0, 0)
            })
          } else {
            this.list = this.list.concat(data)
          }
          this.pageIndex++
          this.loading = false
          this.finished = data.length < this.pageSize
          this.isLoading = false
          this.nodata = this.list.length == 0
        })
        .catch(() => {
          this.loading = false
          this.finished = true
        })
    },
    goForm(n) {
      this.$router.push({
        name:
          n.deviceCategoryId != 0 && n.deviceCategoryId != 114
            ? 'DeviceForm'
            : 'DeviceFormOther',
        params: {
          data: n,
        },
      })
    },
    confirmDel() {
      this.loadingMask = true
      delDevice({
        account: this.userInfo.accountName,
        businessType: this.row.businessType,
        orgId: this.row.orgId,
        recordId: this.row.recordId,
      })
        .then(({ status, info }) => {
          if (status == 200) {
            this.$toast('操作成功')
            this.search()
          } else {
            this.$toast(info)
          }
          this.show = false
          this.loadingMask = false
        })
        .catch(() => {
          this.show = false
          this.loadingMask = false
        })
    },
    askDel(n) {
      this.row = n
      this.$dialog
        .confirm({
          title: '删除设备',
          message: '确认删除该设备吗？',
          showCancelButton: true,
          confirmButtonColor: '#2471CA',
          closeOnClickOverlay: true,
        })
        .then(() => {
          this.confirmDel()
        })
        .catch(() => {})
    },
    back() {
      this.$router.go(-1)
    },
  },
}
</script>
<style lang='scss'>
.add-record {
  .e-search {
    padding: 0 15px;
  }
  &-list {
    position: fixed;
    top: 125px;
    left: 0;
    right: 0;
    bottom: 0;
    overflow-y: auto;
    &.is-tab2 {
      top: 170px;
    }
    .van-loading {
      position: absolute;
      top: 0;
      left: 50%;
      transform: translateX(-50%);
    }
  }
  &-item {
    box-shadow: 0 2px 12px 0 rgba(181, 200, 206, 0.5);
    border-radius: 6px;
    .van-button {
      height: 30px;
      line-height: 30px;
    }
  }

  .van-pull-refresh {
    min-height: calc(100vh -180px);
  }
}
.popover-device-filter {
  .van-popover__arrow {
    left: initial !important;
    right: 5px;
  }
}
</style>